﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TextBox = System.Windows.Controls.TextBox;

namespace ConfigCreate.Controls
{
    /// <summary>
    /// CreateControlIpAddressTextBox.xaml 的交互逻辑
    /// </summary>
    public partial class CreateControlIpAddressTextBox : System.Windows.Controls.UserControl
    {
        /// <summary>
        /// IP地址变动事件
        /// </summary>
        public event EventHandler<EventArgs>? IpAddressChanged;

        /// <summary>
        /// 
        /// </summary>
        public CreateControlIpAddressTextBox()
        {
            InitializeComponent();

            PART_Number1.PreviewTextInput += PART_Number_PreviewTextInput;
            PART_Number2.PreviewTextInput += PART_Number_PreviewTextInput;
            PART_Number3.PreviewTextInput += PART_Number_PreviewTextInput;
            PART_Number4.PreviewTextInput += PART_Number_PreviewTextInput;

            PART_Number1.PreviewKeyDown += PART_Number_PreviewKeyDown;
            PART_Number2.PreviewKeyDown += PART_Number_PreviewKeyDown;
            PART_Number3.PreviewKeyDown += PART_Number_PreviewKeyDown;
            PART_Number4.PreviewKeyDown += PART_Number_PreviewKeyDown;

            PART_Number1.TextChanged += PART_Number_ValueChanged;
            PART_Number2.TextChanged += PART_Number_ValueChanged;
            PART_Number3.TextChanged += PART_Number_ValueChanged;
            PART_Number4.TextChanged += PART_Number_ValueChanged;
        }

        /// <summary>
        /// IP地址的第一个输入框
        /// </summary>
        public double? Number1
        {
            get { return (double?)GetValue(Number1Property); }
            set { SetValue(Number1Property, value); }
        }
        /// <summary>
        /// 第1数字
        /// </summary>
        public static readonly DependencyProperty Number1Property = DependencyProperty.Register("Number1", typeof(double?), typeof(CreateControlIpAddressTextBox));
        /// <summary>
        /// IP地址的第二个输入框
        /// </summary>
        public double? Number2
        {
            get { return (double?)GetValue(Number2Property); }
            set { SetValue(Number2Property, value); }
        }
        /// <summary>
        /// 第2数字
        /// </summary>
        public static readonly DependencyProperty Number2Property = DependencyProperty.Register("Number2", typeof(double?), typeof(CreateControlIpAddressTextBox));
        /// <summary>
        /// IP地址的第三个输入框
        /// </summary>
        public double? Number3
        {
            get { return (double?)GetValue(Number3Property); }
            set { SetValue(Number3Property, value); }
        }
        /// <summary>
        /// 第3数字
        /// </summary>
        public static readonly DependencyProperty Number3Property = DependencyProperty.Register("Number3", typeof(double?), typeof(CreateControlIpAddressTextBox));
        /// <summary>
        /// IP地址的第四个输入框
        /// </summary>
        public double? Number4
        {
            get { return (double?)GetValue(Number4Property); }
            set { SetValue(Number4Property, value); }
        }
        /// <summary>
        /// 第4数字
        /// </summary>
        public static readonly DependencyProperty Number4Property = DependencyProperty.Register("Number4", typeof(double?), typeof(CreateControlIpAddressTextBox));
        /// <summary>
        /// IP地址
        /// </summary>
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
        /// <summary>
        /// IP地址
        /// </summary>
        public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CreateControlIpAddressTextBox), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, OnTextChanged));

        /// <summary>
        /// 是否为只读模式
        /// </summary>
        public bool IsReadOnly
        {
            get { return (bool)GetValue(IsReadOnlyProperty); }
            set { SetValue(IsReadOnlyProperty, value); }
        }
        /// <summary>
        /// 只读
        /// </summary>
        public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(CreateControlIpAddressTextBox), new FrameworkPropertyMetadata(false));

        private static string GetNumberText(string txt)
        {
            if (int.TryParse(txt, out var number))
            {
                number = Math.Min(255, number);
                number = Math.Max(0, number);
                return number.ToString();
            }
            return string.Empty;
        }

        private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CreateControlIpAddressTextBox tbox = (CreateControlIpAddressTextBox)d;
            if (e.NewValue == null)
                return;
            if (e.NewValue.ToString() != GetIPText(tbox))
            {
                var splits = e.NewValue?.ToString()?.Split('.');
                if (splits?.Length >= 1)
                {
                    tbox.PART_Number1.Text = GetNumberText(splits[0]);
                    if (int.TryParse(tbox.PART_Number1.Text, out int p1))
                        tbox.Number1 = p1;
                    else
                        tbox.Number1 = null;
                }
                if (splits?.Length >= 2)
                {
                    tbox.PART_Number2.Text = GetNumberText(splits[1]);
                    if (int.TryParse(tbox.PART_Number2.Text, out int p2))
                        tbox.Number2 = p2;
                    else
                        tbox.Number2 = null;
                }
                if (splits?.Length >= 3)
                {
                    tbox.PART_Number3.Text = GetNumberText(splits[2]);
                    if (int.TryParse(tbox.PART_Number3.Text, out int p3))
                        tbox.Number3 = p3;
                    else
                        tbox.Number3 = null;
                }
                if (splits?.Length >= 4)
                {
                    tbox.PART_Number4.Text = GetNumberText(splits[3]);
                    if (int.TryParse(tbox.PART_Number4.Text, out int p4))
                        tbox.Number4 = p4;
                    else
                        tbox.Number4 = null;
                }
            }
            else
            {
                tbox.IpAddressChanged?.Invoke(tbox, EventArgs.Empty);
            }
        }

        private static string GetIPText(CreateControlIpAddressTextBox tbox)
        {
            return string.Join(".", tbox.PART_Number1.Text, tbox.PART_Number2.Text, tbox.PART_Number3.Text, tbox.PART_Number4.Text);
        }

        private void PART_Number_ValueChanged(object sender, TextChangedEventArgs e)
        {
            this.Text = GetIPText(this);
        }

        private void PART_Number_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (((TextBox)sender).IsReadOnly)
                return;
            Regex re = new Regex("[^0-9]+");
            e.Handled = re.IsMatch(e.Text);
            if (!e.Handled)
            {
                TextBox tbox = (TextBox)sender;
                string txt = tbox.Text;
                string s1 = (tbox.SelectionStart == txt.Length ? txt : txt.Remove(tbox.SelectionStart));
                string intxt = e.Text;
                string s2 = txt.Substring(tbox.SelectionStart + tbox.SelectionLength);

                string ftxt = s1 + intxt + s2;
                //string txt = tbox.Text + e.Text;
                int.TryParse(ftxt, out int num);
                if (num > 255)
                {
                    e.Handled = true;
                }
            }
        }

        private void PART_Number_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Decimal || e.Key == Key.OemPeriod || e.Key == Key.Tab)
            {
                if (sender == PART_Number1)
                {
                    PART_Number2.Focus();
                    PART_Number2.SelectAll();
                }
                if (sender == PART_Number2)
                {
                    PART_Number3.Focus();
                    PART_Number3.SelectAll();
                }
                if (sender == PART_Number3)
                {
                    PART_Number4.Focus();
                    PART_Number4.SelectAll();
                }
                e.Handled = true;
            }
        }
    }
}
